import fs from 'fs';
import JSZip from 'jszip';
import { Blob } from 'node-fetch';
import path from 'path';
import { getAllFiles } from './folder.js';

globalThis.Blob = Blob;
JSZip.support.blob = true;

export default async function (dir, package_info) {
  const dist_url = path.join(dir, 'dist');
  const Entrypoints = [];
  const zip = JSZip();

  // 打包输出文件
  const files = getAllFiles(path.join(dist_url, package_info.targetName));
  files.forEach(file => {
    if (file.endsWith('.map')) return;
    zip.file(file, fs.readFileSync(path.join(dist_url, package_info.targetName, file)));
  });

  // 打包依赖库
  try {
    const libman_txt = fs.readFileSync(path.join(dir, 'libman.json')).toString('utf8');
    const libman = JSON.parse(libman_txt);
    libman.libraries.forEach(lib => {
      const files = getAllFiles(path.join(dir, lib.destination));
      files.forEach(file => {
        const fullname = path.join(lib.library, file);
        zip.file(fullname, fs.readFileSync(path.join(dir, lib.destination, file)));
        if (lib.entrypoints && fullname.toLocaleLowerCase().endsWith('.js')) {
          Entrypoints.push(package_info.targetName + '/' + fullname);
        }
      });
    });
  } catch (e) { }

  // 打包静态资源
  try {
    const files = getAllFiles(path.join(dir, 'public', 'static'));
    files.forEach(file => {
      const fullname = path.join('static', file);
      zip.file(fullname, fs.readFileSync(path.join(dir, 'public', 'static', file)));
    });
  } catch (e) { }

  // 获取入口文件
  try {
    // webpack
    const manifest_txt = fs.readFileSync(path.join(dist_url, 'asset-manifest.json')).toString('utf8');
    const manifest = JSON.parse(manifest_txt);
    Entrypoints.push(...manifest.entrypoints);
  }
  catch (e) {
    // vite
    const manifest_txt = fs.readFileSync(path.join(dist_url, '.vite', 'manifest.json')).toString('utf8');
    const manifest = JSON.parse(manifest_txt);
    Object.values(manifest).forEach(item => {
      Entrypoints.push(item.file);
    });
  }

  const Zip = await zip.generateAsync({ type: 'blob', compression: 'DEFLATE', compressionOptions: { level: 5 } });

  return {
    "ID": package_info.id,
    "Name": package_info.targetName,
    "Code": package_info.targetCode,
    "Version": package_info.version,
    "Info": package_info.description,
    "Author": package_info.author,
    Entrypoints: package_info.preload ? { preload: true, Entrypoints } : Entrypoints,
    Zip,
  };
}